package priv.ln.TCP;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ClassName: TCPTest1
 * Package: priv.ln.TCP
 * Description:
 * 客户端发送内容给服务端，服务端将内容打印到控制台上
 *
 * @Author 辣辣
 * @Create 2024/8/12 17:30
 * @Version 1.0
 */
public class TCPTest1 {
    @Test
    public void client() {
        //1. 创建一个Socket
        Socket socket = null;
        OutputStream os = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            int port = 8080;
            socket = new Socket(inetAddress, port);
            //2. 发送数据
            os = socket.getOutputStream();
            os.write("你好，我是客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3. 关闭socket、关闭流
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Test
    public void server() {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        try {
            //1. 创建一个ServerSocket
            int port = 8080;
            serverSocket = new ServerSocket(port);
            //2. 调用accept()，接收客户端的Socket
            socket = serverSocket.accept();
            System.out.println("收到了来自于" + socket.getInetAddress().getHostAddress() + "的连接");
            //3. 接收数据
            is = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            System.out.println(baos);
            System.out.println("数据接受完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭Socket、ServerSocket、流
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
